package com.iraeta.service.sys.impl;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.iraeta.WeiXinConfig;
import com.iraeta.common.ServiceException;
import com.iraeta.entity.SysOrg;
import com.iraeta.entity.vo.WeiXinOAuthLogin;
import com.iraeta.entity.vo.WeiXinUserInfo;
import com.iraeta.entity.wx.Wxtextmessage;
import com.iraeta.uitl.HttpUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;

@Component
public class WeiXinService {
    private static final Logger logger = LoggerFactory.getLogger(WeiXinService.class);
    @Autowired
    WeiXinConfig weiXinConfig;

    private static String access_token = null;
    private static Date tokenExpireTime = null;

    public String getAccess_token() {
        if (null == access_token || new Date().getTime() > tokenExpireTime.getTime()) {
            return getAccessToken();
        } else {
            return access_token;
        }
    }
    private String getAccessToken(){
        String corpid = weiXinConfig.getCompId();   //企业id
        String secret = weiXinConfig.getAppSecret();
        try {
            String res = HttpUtils.sendGet("https://qyapi.weixin.qq.com/cgi-bin/gettoken", "corpid="+corpid+"&corpsecret="+secret);
            JSONObject jsonObject = JSON.parseObject(res);
            Object accesstoken = jsonObject.get("access_token");
            if (null != accesstoken) {
                access_token = accesstoken.toString();
                tokenExpireTime = DateUtil.offsetMinute(new Date(), 60);
            }
        } catch (Exception e) {
            e.printStackTrace();
            cleanTokenCache();
            throw new ServiceException("微信token获取失败");
        }
        return access_token;
    }
    private void cleanTokenCache() {
        access_token = null;
        tokenExpireTime = null;
    }

    /*
    private static String txl_token = null;
    private static Date txlExpireTime = null;
    public String getTxl_token() {
        if (null == txl_token || new Date().getTime() > txlExpireTime.getTime()) {
            return getTxlToken();
        } else {
            return txl_token;
        }
    }
    private String getTxlToken(){
        String corpid = weiXinConfig.getCompId();   //企业id
        String secret = weiXinConfig.getTxlSecret();
        try {
            String res = HttpUtils.sendGet("https://qyapi.weixin.qq.com/cgi-bin/gettoken", "corpid="+corpid+"&corpsecret="+secret);
            JSONObject jsonObject = JSON.parseObject(res);
            Object accesstoken = jsonObject.get("access_token");
            if (null != accesstoken) {
                txl_token = accesstoken.toString();
                txlExpireTime = DateUtil.offsetMinute(new Date(), 60);
            }
        } catch (Exception e) {
            e.printStackTrace();
            cleanTxlTokenCache();
            throw new ServiceException("微信通讯录token获取失败");
        }
        return txl_token;
    }
    private void cleanTxlTokenCache() {
        txl_token = null;
        txlExpireTime = null;
    }
     */

    public WeiXinOAuthLogin getUserIdByCode(String code){
        String token = this.getAccess_token();
        try{
            String res = HttpUtils.sendGet("https://qyapi.weixin.qq.com/cgi-bin/auth/getuserinfo", "access_token="+token+"&code="+code);
            JSONObject jsonObject = JSON.parseObject(res);
            logger.info(jsonObject.toJSONString());
            String userid = jsonObject.getString("userid");
            String user_ticket = jsonObject.getString("user_ticket");
            if (null == userid) {
                throw new ServiceException("微信身份获取失败1");
            }
            return new WeiXinOAuthLogin(userid, user_ticket);
        }catch (Exception e){
            e.printStackTrace();
            throw new ServiceException("微信身份获取失败1");
        }
    }

    public WeiXinUserInfo getWeiXinUserInfo(String user_ticket){
        String token = this.getAccess_token();
        try {
            JSONObject body = new JSONObject();
            body.put("user_ticket", user_ticket);
            String res = HttpUtils.httpPost("https://qyapi.weixin.qq.com/cgi-bin/auth/getuserdetail?access_token=" + token, body.toJSONString());
            JSONObject jsonObject = JSON.parseObject(res);
            logger.info(jsonObject.toJSONString());
            String userid = jsonObject.getString("userid");
            String mobile = jsonObject.getString("mobile");
            String avatar = jsonObject.getString("avatar");
            if(null == userid){
                throw new ServiceException("微信身份获取失败2");
            }
            return new WeiXinUserInfo(userid, mobile, avatar);
        }catch (Exception e){
            e.printStackTrace();
            throw new ServiceException("微信身份获取失败2");
        }
    }

    public List<SysOrg> getWeiXinOrg(){
        String token = this.getAccess_token();
        try{
            String res = HttpUtils.sendGet("https://qyapi.weixin.qq.com/cgi-bin/department/list", "access_token="+token);
            JSONObject jsonObject = JSON.parseObject(res);
            logger.info(jsonObject.toJSONString());
            int errcode = jsonObject.getIntValue("errcode");
            if(errcode!=0){
                throw new ServiceException("微信部门列表获取失败");
            }
            JSONArray deptJSONArray = jsonObject.getJSONArray("department");
            List<SysOrg> sysOrgList = new ArrayList<>();
            for(int i = 0; i<deptJSONArray.size();i++){
                JSONObject deptJSONObject = deptJSONArray.getJSONObject(i);
                SysOrg sysOrg = new SysOrg();
                sysOrg.setId(deptJSONObject.getIntValue("id"));
                sysOrg.setPid(deptJSONObject.getIntValue("parentid"));
                sysOrg.setName(deptJSONObject.getString("name"));
                sysOrgList.add(sysOrg);
            }
            return sysOrgList;
        }catch (Exception e){
            e.printStackTrace();
            throw new ServiceException("微信部门列表获取失败:" + e.getMessage());
        }
    }

    public List<WeiXinUserInfo> getOrgWeiXinUserInfo(int orgId){
        String token = this.getAccess_token();
        try{
            String res = HttpUtils.sendGet("https://qyapi.weixin.qq.com/cgi-bin/user/list", "access_token="+token+"&department_id="+orgId);
            JSONObject jsonObject = JSON.parseObject(res);
            logger.info(jsonObject.toJSONString());
            int errcode = jsonObject.getIntValue("errcode");
            if(errcode!=0){
                throw new ServiceException("微信获取部门成员详情失败");
            }
            JSONArray userJSONArray = jsonObject.getJSONArray("userlist");
            List<WeiXinUserInfo> weiXinUserInfoList = new ArrayList<>();
            for(int i = 0; i<userJSONArray.size();i++){
                JSONObject userJSONObject = userJSONArray.getJSONObject(i);
                WeiXinUserInfo sysOrg = new WeiXinUserInfo(userJSONObject.getString("userid"), userJSONObject.getString("name"));
                weiXinUserInfoList.add(sysOrg);
            }
            return weiXinUserInfoList;
        }catch (Exception e){
            e.printStackTrace();
            throw new ServiceException("微信获取部门成员详情失败:" + e.getMessage());
        }
    }

    public String setWxUserTextMessage(Wxtextmessage wxtextmessage){
        String token = this.getAccess_token();
        try {
            JSONObject body = new JSONObject();
            body.put("agentid", weiXinConfig.getAppId());
            body.put("msgtype", "text");
            body.put("safe", 0);
            body.put("enable_id_trans", 0);
            body.put("enable_duplicate_check", 0);
            body.put("duplicate_check_interval", 1800);

            body.put("touser", wxtextmessage.getTouser());
            Map<String, String> text = new HashMap<>();
            text.put("content", wxtextmessage.getContent());
            body.put("text", text);
            String res = HttpUtils.httpPost(" https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=" + token, body.toJSONString());
            JSONObject jsonObject = JSON.parseObject(res);
            int errcode = jsonObject.getIntValue("errcode");
            if(errcode!=0){
                throw new ServiceException(jsonObject.getString("errmsg"));
            }
        }catch (Exception e){
            e.printStackTrace();
            return e.getMessage();
        }
        return "";
    }
}
